import 'package:dio/dio.dart';
import 'package:kepu/model/common_list_page_entity.dart';
import 'package:kepu/util/http_util.dart';
import 'package:riverpod_annotation/riverpod_annotation.dart';

part 'search_provider.g.dart';

@riverpod
class Search extends _$Search {
  int page = 1;
  @override
  FutureOr<List<CommonListPageDataRecords>> build() async {
    return [];
  }
  Future<void> search({required String keyword})async{
    var searchOption = ref.watch(searchOptionProvider);
    Response response;
    if (searchOption == "搜动物") {
      response = await DioInstance.instance().get(
        path: "search/animal?current=1&size=10&keyword=$keyword",
      );
    } else {
      response = await DioInstance.instance().get(
        path: "search/plant?current=1&size=10&keyword=$keyword",
      );
    }
    state = AsyncValue.data(CommonListPageEntity.fromJson(response.data).data.records);
  }

  Future<void> add({required String keyword}) async {
    page ++;
    Response response;
    var searchOption = ref.watch(searchOptionProvider);
    if (searchOption == "搜动物") {
      response = await DioInstance.instance().get(
        path: "search/animal?current=$page&size=10&keyword=$keyword",
      );
    } else {
      response = await DioInstance.instance().get(
        path: "search/plant?current=$page&size=10&keyword=$keyword",
      );
    }
    var records = CommonListPageEntity
        .fromJson(response.data)
        .data
        .records;
    if (records.isNotEmpty) {
      state = AsyncValue.data([...state.value!, ...records]);
    }
  }
}

@riverpod
class SearchOption extends _$SearchOption {
  @override
  String build() {
    return "搜植物";
  }

  void switchItem(String item) {
    state = item;
  }
}
